package com.xzlf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzlf.domain.WebSite;
import com.xzlf.service.WebSiteService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzlf.mapper.NovelChapterMapper;
import com.xzlf.domain.NovelChapter;
import com.xzlf.service.NovelChapterService;
@Service
public class NovelChapterServiceImpl extends ServiceImpl<NovelChapterMapper, NovelChapter> implements NovelChapterService{

    @Autowired
    private WebSiteService webSiteService;

    @Override
    public List<NovelChapter> findByPage(int pid, int current, int pageSize) {
        WebSite webSite = webSiteService.getById(pid);

        Page<NovelChapter> page = page(new Page<NovelChapter>(current, pageSize),
                new LambdaQueryWrapper<NovelChapter>()
                        .eq(pid != 0, NovelChapter::getPid, pid));
        List<NovelChapter> records = page.getRecords();
        for (NovelChapter record : records) {
            record.setContentUrl(webSite.getUrl() + record.getUri());
        }
        return records;
    }


    @Override
    public String getContent(String url, int pid) {
        WebSite webSite = webSiteService.getById(pid);
        Document document = null;
        try {
            document = Jsoup.connect(url).get();
            Document parse = Jsoup.parse(document.html());
            Elements elements = parse.select(webSite.getContentSelect());
//            System.out.println(elements.size());
            String text = elements.get(0).html();
//            System.out.println(text);
            return text;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
